import {GetQtController} from "./QtUtils";
import {FrameManager} from "./frame/FrameManager";
import {PUBSUB_KEY_SERVER_WEBSOCKET} from "./QtBaseController";

export const SERVER_WS_CONNECT_SUCCESS = 'connect_success'; //初始化成功
export const SERVER_WS_CONNECT_FAIL = 'connect_fail'; //初始化失败
export const SERVER_WS_DO_NEXT = 'do_next'; //接下来

export default class ServerWebSocket
{
    constructor(strServerIp,serverPort,fnInitConnectCallback)
    {
        this.isConnected = false;
        this.strServerIp = strServerIp;
        this.serverPort = serverPort;
        //this.fnConnectCallback = (isConnected),isConnected:true 成功，false失败
        this.fnConnectCallback = fnInitConnectCallback;
        this.mWebsocket = null;

        this.initDataManager();
    }

    initDataManager()
    {
		  this.startConnect();
    }

    startConnect()
    {
        let preHost = 'ws://';
        if(GetQtController().inParam.dataUrl.indexOf('https') != -1) {
          preHost = 'wss://';
        }
        console.log('ServerWebSocket',preHost + this.strServerIp + ':'+String(this.serverPort)+'/ws');
        this.mWebsocket = new WebSocket(preHost + this.strServerIp + ':'+String(this.serverPort)+'/ws');
        if(!this.mWebsocket)
        {
            console.log('ServerWebSocket','ServerWebSocket connect failed!')
            if(this.fnConnectCallback) {
              this.fnConnectCallback(SERVER_WS_CONNECT_FAIL);
            }
            return;
        }

        this.mWebsocket.binaryType = 'arraybuffer';
        this.mWebsocket.onopen = this.onAppSocketOpen.bind(this);
        this.mWebsocket.onmessage = this.onAppData.bind(this);
        this.mWebsocket.onerror = this.onError.bind(this);
        this.mWebsocket.onclose = this.onClose.bind(this);
        window.addEventListener("beforeunload", function (e) {
          if(this.webAppSocket) {
            this.webAppSocket.close();
          }
        });

    }

    startReConnectTimer() {
        // this.isReconneccted = true;
        // setTimeout(() => {
        //     this.startAppSocket();
        // }, 2000);
    }

    onClose(event) {
        console.log('onClose',event);
        this.isConnected = false;
        this.startReConnectTimer();
    }

    onError(event) {
        console.log('onError',event);
        this.isConnected = false;
        if(this.fnConnectCallback) {
            this.fnConnectCallback(SERVER_WS_CONNECT_FAIL);
            this.fnConnectCallback = null;
        }
    }

    onAppSocketOpen()
    {
      if(this.mWebsocket.readyState === WebSocket.OPEN)
      {
        this.isConnected = true;
      } else {
        console.log('ServerWebSocket',"socket is not connected yet");
      }

      if(this.fnConnectCallback) {
        this.fnConnectCallback(this.isConnected?SERVER_WS_CONNECT_SUCCESS:SERVER_WS_CONNECT_FAIL);
      }
      console.log('ServerWebSocket','onAppSocketOpen--' + this.strServerIp + ':'+String(this.serverPort));
    }

    onAppData(event)
    {
      let strData = event.data;
      console.log('ServerWebSocket,onAppData',strData);
      if(GetQtController().GetInParam().isLog) {
        console.log('ServerWebSocket',strData);
      }
      if(!(typeof(strData)=='string')) {
        //不是String则返回
        return;
      }

      FrameManager.getInstance().sendPubSubMessage(PUBSUB_KEY_SERVER_WEBSOCKET,JSON.parse(strData));
	}

    sendAppText(text)
    {
        if(this.isConnected)
        {
            this.mWebsocket.binaryType = 'blob';
            this.mWebsocket.send(text);
        }
    }
    // ________________________________________________

    close() {
        if(this.mWebsocket) {
          this.mWebsocket.close();
        }
    }
}
